package com.design.graduation.asdemo.controller;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.Poi;
import com.amap.api.maps.overlay.PoiOverlay;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.core.SuggestionCity;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.InputtipsQuery;
import com.amap.api.services.help.Tip;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.design.graduation.asdemo.R;
import com.design.graduation.asdemo.base.ActionBarActivity;
import com.design.graduation.asdemo.event.BusProvider;
import com.design.graduation.asdemo.event.PositionInfo;
import com.design.graduation.asdemo.model.InfoEntity;
import com.design.graduation.asdemo.utils.AMapUtil;
import com.design.graduation.asdemo.utils.LogUtils;
import com.design.graduation.asdemo.utils.ToastUtil;
import com.design.graduation.asdemo.view.TipsDialog;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by lijinyuan on 16/3/1.
 */
public class LocationActivity extends ActionBarActivity implements
        CompoundButton.OnCheckedChangeListener, AMapLocationListener,
        LocationSource, TextWatcher, PoiSearch.OnPoiSearchListener,
        Inputtips.InputtipsListener, AMap.OnPOIClickListener, AMap.OnMarkerClickListener {
    protected AMap aMap;
    protected MapView mapView;
    private TipsDialog tipsDialog;
    private AMapLocationClient aMapLocationClient;
    private LocationSource.OnLocationChangedListener listener;
    private AutoCompleteTextView searchEdit;
    private Button searchButton;
    String keyWord;
    private PoiSearch.Query query;// Poi查询条件类
    private PoiResult poiResult; // poi返回的结果
    private PoiSearch poiSearch;// POI搜索
    private InfoEntity position;
    private String city;

    private Boolean isShow;
    //定位参数设置
    private AMapLocationClientOption aMapLocationClientOption;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_location);

        BusProvider.register(this);
        searchEdit = (AutoCompleteTextView) findViewById(R.id.position_edit);
        searchButton = (Button) findViewById(R.id.position_button);
        mapView = (MapView) findViewById(R.id.aMap);
        mapView.onCreate(savedInstanceState);
        position = new InfoEntity();
        if (aMap == null) {
            aMap = mapView.getMap();
        }

        setToolBar();
        setUpMap();
        aMap.setOnPOIClickListener(this);
        aMap.setOnMarkerClickListener(this);
        searchEdit.addTextChangedListener(this);
        setPosition();

    }


    private void setUpMap() {
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);
        MyLocationStyle locationStyle = new MyLocationStyle();
//        locationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher));
        locationStyle.strokeColor(Color.BLUE);
        locationStyle.strokeWidth(5);
        aMap.setMyLocationStyle(locationStyle);

        // 设置定位监听
        aMap.setLocationSource(this);
        aMap.getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        // 设置定位的类型为定位模式，参见类AMap。
        aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
        // 设置为true表示系统定位按钮显示并响应点击，false表示隐藏，默认是false
        aMap.setMyLocationEnabled(true);

        aMapLocationClient = new AMapLocationClient(getApplicationContext());
        aMapLocationClient.setLocationListener(this);

        //初始化定位参数
        aMapLocationClientOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        aMapLocationClientOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        aMapLocationClientOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        aMapLocationClientOption.setOnceLocation(true);
        //设置是否强制刷新WIFI，默认为强制刷新
        aMapLocationClientOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        aMapLocationClientOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        aMapLocationClientOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        aMapLocationClient.setLocationOption(aMapLocationClientOption);
        //启动定位
        aMapLocationClient.startLocation();


    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mapView != null && outState != null) {
            mapView.onSaveInstanceState(outState);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mapView != null) {
            mapView.onDestroy();
        }
        if (aMapLocationClient != null) {
            aMapLocationClient.onDestroy();
            aMapLocationClient = null;
            aMapLocationClientOption = null;
        }
        BusProvider.unregister(this);
    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {

        if (listener != null && aMapLocation != null) {
            listener.onLocationChanged(aMapLocation);// 显示系统小蓝点
            if (aMapLocation.getErrorCode() == 0) {
                //定位成功回调信息，设置相关消息
                aMapLocation.getLocationType();//获取当前定位结果来源，如网络定位结果，详见定位类型表
                aMapLocation.getLatitude();//获取经度
                aMapLocation.getLongitude();//获取纬度;
                aMapLocation.getAccuracy();//获取精度信息
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = new Date(aMapLocation.getTime());
                df.format(date);//定位时间
//                aMapLocation.getAddress();//地址，如果option中设置isNeedAddress为false，则没有此结果
//                aMapLocation.getCountry();//国家信息
//                aMapLocation.getProvince();//省信息
//                aMapLocation.getCity();//城市信息
//                aMapLocation.getDistrict();//城区信息
//                aMapLocation.getRoad();//街道信息
//                aMapLocation.getCityCode();//城市编码
//                aMapLocation.getAdCode();//地区编码
                city = aMapLocation.getCity();//城市信息
//                positionDetails = aMapLocation.getProvince() + aMapLocation.getCity() + aMapLocation.getDistrict() + aMapLocation.getRoad();
            } else {
                //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                Log.e("Tomato", "location Error, ErrCode:"
                        + aMapLocation.getErrorCode() + ", errInfo:"
                        + aMapLocation.getErrorInfo());

            }
        }
    }

    @Override
    public void activate(OnLocationChangedListener onLocationChangedListener) {
        listener = onLocationChangedListener;
    }

    @Override
    public void deactivate() {

    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        MenuItem text = menu.findItem(R.id.action_text);
        MenuItem img = menu.findItem(R.id.action_img);
        text.setVisible(false);
        if (position == null) {
            img.setCheckable(false);
            ToastUtil.showShortToast("请选择您的位置");
        }
        img.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                if (position.getLon() != 0 && position.getLat() != 0 && position.getAddress() != null) {
                    BusProvider.post(new PositionInfo(position));
                    finish();
                } else ToastUtil.showShortToast("请输入正确地址");
                return true;
            }
        });
        return true;
    }

    private void setToolBar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("定位");
        setSupportActionBar(toolbar);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String newText = s.toString().trim();
        if (!AMapUtil.IsEmptyOrNullString(newText)) {
            InputtipsQuery inputquery = new InputtipsQuery(newText, city);
            Inputtips inputTips = new Inputtips(LocationActivity.this, inputquery);
            inputTips.setInputtipsListener(this);
            inputTips.requestInputtipsAsyn();
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    @Override
    public void onPoiSearched(PoiResult result, int i) {
        if (i == 1000) {
            if (result != null && result.getQuery() != null) {// 搜索poi的结果
                if (result.getQuery().equals(query)) {// 是否是同一条
                    poiResult = result;
                    // 取得搜索到的poiitems有多少页
                    List<PoiItem> poiItems = poiResult.getPois();// 取得第一页的poiitem数据，页数从数字0开始
                    List<SuggestionCity> suggestionCities = poiResult
                            .getSearchSuggestionCitys();// 当搜索不到poiitem数据时，会返回含有搜索关键字的城市信息

                    if (poiItems != null && poiItems.size() > 0) {
                        aMap.clear();// 清理之前的图标
                        PoiOverlay poiOverlay = new PoiOverlay(aMap, poiItems);
                        poiOverlay.removeFromMap();
                        poiOverlay.addToMap();
                        poiOverlay.zoomToSpan();
                    } else if (suggestionCities != null
                            && suggestionCities.size() > 0) {
                        ToastUtil.showShortToast("没有找到");

                    } else {
                        ToastUtil.showShortToast("没有找到");

                    }
                }
            } else {
                ToastUtil.showShortToast("没有找到");

            }
        } else {
            ToastUtil.showShortToast("没有找到");
        }

    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    private void setPosition() {
        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                keyWord = AMapUtil.checkEditText(searchEdit);
                if ("".equals(keyWord)) {
                    ToastUtil.showShortToast("请输入位置");
                    return;
                } else {
                    query = new PoiSearch.Query(keyWord, "", city);// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
                    query.setPageSize(5);// 设置每页最多返回多少条poiitem
                    query.setPageNum(1);// 设置查第一页

                    poiSearch = new PoiSearch(LocationActivity.this, query);
                    poiSearch.setOnPoiSearchListener(LocationActivity.this);
                    poiSearch.searchPOIAsyn();
                }
            }

        });


    }

    @Override
    public void onGetInputtips(List<Tip> tipList, int rCode) {
        if (rCode == 1000) {// 正确返回
            List<String> listString = new ArrayList<String>();
            for (int i = 0; i < tipList.size(); i++) {
                listString.add(tipList.get(i).getName());
            }
            ArrayAdapter<String> aAdapter = new ArrayAdapter<String>(
                    getApplicationContext(),
                    R.layout.route_inputs, listString);
            searchEdit.setAdapter(aAdapter);
            aAdapter.notifyDataSetChanged();
        } else {
            ToastUtil.showShortToast("错误码" + rCode);
        }

    }

    @Override
    public boolean onMarkerClick(final Marker marker) {

        if (tipsDialog == null) {
            tipsDialog = new TipsDialog(LocationActivity.this, new TipsDialog.EnsureOrCancelListener() {
                @Override
                public void onEnsureClicked() {
                    LatLng latLng = marker.getPosition();
                    LogUtils.d(latLng);
                    position.setLat(latLng.latitude);
                    position.setLon(latLng.longitude);
                }

                @Override
                public void onCancelClicked() {
                    tipsDialog.dismiss();
                }
            }, "是否要修改为当前位置?");
        }
        tipsDialog.show();

        return false;
    }

    @Override
    public void onPOIClick(Poi poi) {
        aMap.clear();
        MarkerOptions markOptiopns = new MarkerOptions();
        markOptiopns.position(poi.getCoordinate());
        TextView textView = new TextView(getApplicationContext());
        textView.setText(poi.getName());
        position.setAddress(poi.getName());
        LogUtils.d(poi.getName());
        textView.setGravity(Gravity.CENTER);
        textView.setTextColor(Color.BLACK);
        textView.setBackgroundResource(R.drawable.custom_info_bubble);
        markOptiopns.icon(BitmapDescriptorFactory.fromView(textView));
        isShow = false;
        aMap.addMarker(markOptiopns);
    }

}
